const router = require('koa-router')()
const mongoose = require('mongoose')
const statsfn = require('../lib/statsfn')
const Image = mongoose.model('Image')

router.get('/', async (ctx, next) => {
  ctx.session.user = 'doc'
  const images = await Image.find({})
    .sort({createdAt: -1}).limit(20)
    const stats = await statsfn()
  await ctx.render('index', {
    title: '图片分享',
    images,stats,username: ctx.session.username
  })
})

router.get('/login', async ctx =>{
  await ctx.render('login',{})
})

router.post('/login', async ctx =>{
  const{username, password} =ctx.request.body
  if(username === 'tom' && password === '123'){
    ctx.session.username =username
    ctx.redirect('/')
  }else{
    ctx.redirect('/login') 
  }
    
})

router.get('/logout', async ctx=> {
  ctx.session.username = undefined
  ctx.redirect('/login')
})
module.exports = router
